using Admin2025.Domain.Entities;
using Admin2025.Domain.Repositories;
using Admin2025.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Admin2025.Infrastructure.Repositories;

public class EfRepository<T> : IRepository<T> where T : EntityBase
{
  // 数据库上下文 依赖注入
  private readonly Admin2025DbContext _db;  // 是需要注册的哦！
  private readonly DbSet<T> _tb;
  public EfRepository(Admin2025DbContext db)
  {
    _db = db;
    _tb = _db.Set<T>();
  }

  public async Task<T> CreateAsync(T entity)
  {
    var obj = await _tb.AddAsync(entity);
    await _db.SaveChangesAsync();
    return obj.Entity;
  }

  public async Task DeleteAsync(T entity)
  {
    // 硬删除，即真的删除
    // _tb.Remove(entity);

    // 软删除
    entity.IsDeleted = true;
    await UpdateAsync(entity);
  }

  public async Task<IEnumerable<T>> GetAllAsync()
  {
    // AsNoTracking()：可以提升速度，不进行跟踪
    var list = await _tb.AsNoTracking().ToListAsync();
    return list;
  }

  public async Task<T?> GetByIdAsync(Guid id)
  {
    var obj = await _tb.FindAsync(id);
    return obj;
  }

  public async Task UpdateAsync(T entity)
  {
    entity.UpdatedAt = DateTime.UtcNow;
    _tb.Update(entity);
    await _db.SaveChangesAsync();
  }

  public async Task<IQueryable<T>> GetPagedAsync(int pageIndex, int pageSize)
  {
    var list = await _tb.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
    return list.AsQueryable();
  }
}